package com.woniu.tms.manage.service.impl;

import com.woniu.tms.entity.DB;
import com.woniu.tms.manage.service.DataService;
import com.woniu.tms.manage.utils.MyUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class DataServiceImpl implements DataService {

    @Override
    public Boolean backup(ServletContext context) {
        Boolean flag = false;
        String savePath = context.getRealPath("/data/user");
        String fileName = "temp";
        try {
            MyUtils.exportDatabaseTool("172.16.13.13", "root", "123456", savePath, fileName, "tms");
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    @Override
    public List<DB> indexDo(HttpServletRequest request) {
        List<DB> dbList = new ArrayList<>();
        String path = request.getSession().getServletContext().getRealPath("datas");
        File file = new File(path);
        File[] files = file.listFiles();
        if (files.length != 0) {
            for (File f : files) {
                DB db = new DB();
                db.setName(f.getName().substring(0, f.getName().lastIndexOf(".")));
                db.setPath(f.getPath());
                dbList.add(db);
            }
        }
        return dbList;
    }

    @Override
    public Boolean recover(HttpServletRequest request, String name) {
        String filePath = request.getSession().getServletContext().getRealPath("datas") + "/" + name + ".sql";
        return MyUtils.recover(filePath, "127.0.0.1", "tms", "root", "123456");
    }

}
